package cli

import (
	"os"
	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/routers"
	"time"

	"github.com/kardianos/service"
	"github.com/labstack/echo"
	log "github.com/sirupsen/logrus"
	"github.com/tylerb/graceful"
)

func startServer() {
	e := echo.New()
	routers.SetupMiddlewares(e)
	routers.SetupRoutes(e)
	e.Server.Addr = ":" + base.Context.Server.HTTPPort
	graceful.ListenAndServe(e.Server, 5*time.Second)
}

type program struct{}

func (p *program) Start(s service.Service) error {
	go p.run()
	return nil
}

func (p *program) run() {
	startServer()
}

func (p *program) Stop(s service.Service) error {
	return nil
}

func Service() {
	ParseOptions()
	var err error
	if Opts.Share {
		err = buildShare()
		if err == nil {
			err = buildDictionary()
		}
		os.Exit(1)
	}
	if err != nil {
		log.Error(err.Error())
		os.Exit(1)
	}
	svcConfig := &service.Config{
		Name:        "pas",  //服务显示名称
		DisplayName: "绩效考核", //服务名称
		Description: "绩效考核", //服务描述

	}
	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Error(err)
	}
	if Opts.Install {
		err := s.Install()
		if err != nil {
			log.Println(err.Error())
			return
		}
		log.Println("服务安装成功")
		return
	}
	if Opts.Uninstall {
		s.Uninstall()
		if err != nil {
			log.Println(err.Error())
			return
		}
		log.Println("服务卸载成功")
		return
	}
	err = s.Run()
	if err != nil {
		log.Error(err)
	}
}
